const {exec,escape} = require('../db/mysql.js');
function getList(author,keyword){
	let sql = `select * from blogs where 1=1 `;
	if(author){
		author = escape(author);
		sql += `and author = ${author} `;
	}
	if(keyword){
		// keyword = `%${escape(keyword)}%`;
		sql += `and title like '%${keyword}%' `;
	}
	sql += `order by id desc;`;
	return exec(sql);
}

function getDetail(id,res){
	if(id){
		id = escape(id);
		let sql = `select * from blogs where id = ${id};`;
		return exec(sql);
	}else{
		res.json({errno:-1,msg:"请输入查询ID"});
		return;
	}
}

function del(id,author){
		author = escape(author);
		id = escape(id);
		let sql = `delete from blogs where id = ${id} and author = ${author};`;
		return exec(sql);
}

function newBlog(newBlogData={}){
	const title = newBlogData.title;
	const content = newBlogData.content;
	const author = newBlogData.author;
	const createTime = +new Date();
	let sql = `insert into blogs (title,content,author,createTime) values ('${title}','${content}','${author}','${createTime}')`;
	return exec(sql);
}

function updateBlog(id,update={}){
	id = escape(id);
	let title = escape(update.title);
	let content = escape(update.content);
	let sql = `update blogs set title = ${title},content = ${content} where id = ${id};`;
	return exec(sql);
}

module.exports = {
	getList,
	getDetail,
	del,
	newBlog,
	updateBlog
};
